package wenjun.du.androidart

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class FruitAdapter(val context: Context, private val list: List<Fruit>) :
    RecyclerView.Adapter<FruitAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val fruitImage: ImageView = view.findViewById<ImageView>(R.id.fruitImage)
        val fruitText: TextView = view.findViewById<TextView>(R.id.fruitName)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val holder =
            ViewHolder(
                LayoutInflater.from(context).inflate(R.layout.fruit_item_main, parent, false)
            )
        //        设置adapter的点击事件
        holder.itemView.setOnClickListener {
            val index = holder.adapterPosition
            val item = list[index]
            val intent = Intent(context, list[index].classT).apply {
                putExtra("name", item.name)
            }

            context.startActivity(intent)
        }
        return holder

    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit = list[position]
        Glide.with(context).load(fruit.id).into(holder.fruitImage)
        holder.fruitText.text = fruit.name
    }

    override fun getItemCount(): Int {
        return list.size
    }
}